package com.tuniu.agents.impl.trip;

import com.tuniu.agents.advisor.ChatEnvironmentMemory;
import com.tuniu.agents.agent.AgentManagerGroup;
import com.tuniu.agents.agent.AgentOptions;
import com.tuniu.agents.agent.OptionsAgent;
import com.tuniu.agents.common.message.BaseAgentNewResp;
import com.tuniu.agents.util.HttpManager;
import com.tuniu.agents.util.JsonUtil;
import com.tuniu.agents.util.WebClientManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.Message;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Flux;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class Compare extends OptionsAgent {
    public static final String AGENT_ID = "COMPARE_AGENT";
    public static final String PROMPT_ID = "trip_compare_agent";
    public static final String TRIP_COMPARE_KEY = "TRIP_COMPARE_KEY";

    private final String tripCompareTargetUrl;
    private final Map<String, String> headers;
    private final HttpManager httpManager;
    private final ChatEnvironmentMemory chatEnvironmentMemory;

    public Compare(AgentManagerGroup agentManagerGroup,
                       String agentId,
                       String promptTemplatedId,
                       String tripCompareTargetUrl,
                       ChatEnvironmentMemory chatEnvironmentMemory) {
        this(agentManagerGroup, agentId, promptTemplatedId, tripCompareTargetUrl, new HashMap<>(), chatEnvironmentMemory);
    }
    
    public Compare(AgentManagerGroup agentManagerGroup,
                       String agentId,
                       String promptTemplatedId,
                       String tripCompareTargetUrl,
                       Map<String, String> headers,
                       ChatEnvironmentMemory chatEnvironmentMemory) {
        super(agentManagerGroup, new AgentOptions(agentId, promptTemplatedId));
        this.tripCompareTargetUrl = tripCompareTargetUrl;
        this.headers = headers;
        this.httpManager = new WebClientManager();
        this.chatEnvironmentMemory = chatEnvironmentMemory;
    }
    
    @Override
    public Flux<String> stream(String conversationId, List<Message> messages, Map<String, Object> context) {
        String message = messages.get(0).getText();
        log.info("TripCompareAgent processing session data: {}, Product ID list: {}", conversationId, message);
        try {
            String comparison = call(conversationId, message);
            return Flux.just(comparison);
        } catch (Exception e) {
            log.error("TripCompareAgent: Error processing product comparison", e);
            return Flux.just(BaseAgentNewResp.sendAnswerMsg(null, "Failed to get product comparison: " + e.getMessage()));
        }
    }

    @Override
    public String call(String conversationId,List<Message> messages, Map<String, Object> context) {
        String productIds = messages.get(0).getText();
        if (StringUtils.isEmpty(productIds)) {
            return "Please provide at least two product IDs for comparison.";
        }
        
        log.info("TripCompareAgent calling comparison service, product list: {}", productIds);
        try {
            List<String> productIdList = Arrays.stream(productIds.split(","))
                    .map(String::trim)
                    .filter(id -> !id.isEmpty())
                    .collect(Collectors.toList());
            if (productIdList.size() < 2) {
                return "At least two product IDs are required for comparison analysis.";
            }
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("productIds", productIdList);
            String response = httpManager.post(tripCompareTargetUrl, requestBody, String.class, headers);
            log.info("TripCompareAgent received product comparison response, product list: {}, response content: {}", productIds, response);
            if (response == null || response.isEmpty()) {
                return "Sorry, could not retrieve product comparison information.";
            }
            // Parse response and extract comparison suggestions
            Map<String, Object> responseMap = JsonUtil.fromJson(response, Map.class);
            if (responseMap != null && responseMap.containsKey("comparison")) {
                String comparison = (String) responseMap.get("comparison");
                Map<String, Object> comparedResponse = new HashMap<>();
                comparedResponse.put(TRIP_COMPARE_KEY, comparison);
                chatEnvironmentMemory.add(conversationId, responseMap);
                return comparison;
            } else {
                return "Unable to retrieve product comparison information, please try again later.";
            }
        } catch (Exception e) {
            log.error("TripCompareAgent: Error calling comparison service", e);
            return "An error occurred while retrieving product comparison information, please try again later.";
        }
    }

} 